from flask import Flask, request
from flask_cors import CORS
import requests
import json
from results import *
import utils
from mysql_util import *
from hashlib import md5
import redis_utils
from service import *
import operator_db_create

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
CORS(app, supports_credentials=True)


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/v1/level3/clientVersionGet', methods=['GET'])
def get_client_verion():
    d = {"jsonrpc": "2.0", "method": "getClientVersion", "params": [], "id": 1}
    return common_request(d)


@app.route('/v1/level3/blockNumberGet', methods=['GET'])
def get_block_number():
    d = {"jsonrpc": "2.0", "method": "getBlockNumber", "params": [1], "id": 1}
    return common_request(d)


@app.route('/v1/login', methods=['POST'])
def login():
    dict = request.json
    # 判断username和password参数是否在request请求中
    if not utils.has_keys(dict, 'username', 'password'):
        return info_incomplete_result

    conn = get_conn()
    cursor = get_cursor(conn)

    query_user_sql = f"select * from user where username = '{dict['username']}'"
    res = exec_sql(conn, cursor, query_user_sql)[0]
    release(conn, cursor)

    md5_passwd = md5(dict['password'].encode('utf8')).hexdigest()
    # 将输入密码与数据库用户的密码匹配
    if md5_passwd == res[1]:
        # 如果密码匹配，处理用户token信息，存入redis数据库
        token = utils.gen_token()  # 生成token
        # 在数据库中存储以token为key，username为value的键值对
        redis_utils.set_value(token, dict['username'])
        # 返回包含token的内容
        msuccess_result = json.dumps({'code': 200, 'data': {'content': 'ok', 'token': token}})

        return msuccess_result
    else:
        # 若信息有误返回通用result
        return login_failed_result


@app.route('/v1/tokenVerify', methods=['GET'])
def token_verify():
    token = request.args.get('token')
    username = redis_utils.get_value(token)
    if not username:
        return token_empty_result
    return success_result


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5003)
